package com.redis.hash;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import redis.clients.jedis.Jedis;

public class RedisHash {
	public static void main(String[] args) {
		jedisErgodicHash();
	}
	
	/**
	 * 遍历Hash表
	 */
	public static void jedisErgodicHash() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		Iterator<String> it = jedis.hkeys("user").iterator();
		while (it.hasNext()) {
			String key = it.next();
			System.out.println(key + " :" + jedis.hget("user", key));
		}
		jedis.close();
	}
	
	/**
	 * 删除Hash表的一个字段
	 */
	public static void jedisDeleteHashField() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		jedis.hdel("user", "age");
		jedis.close();
	}
	
	/**
	 * 判读Hash表是否存在
	 */
	public static void jedisExistsHashKey() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		System.out.println(jedis.exists("user"));
		jedis.close();
	}
	
	/**
	 * 获取Hash表的长度
	 */
	public static void jedisGetHashLength() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		System.out.println(jedis.hlen("user"));
		jedis.close();
	}
	
	/**
	 * 获取Hash表所有字段的值
	 */
	public static void jedisGetHashFieldValues() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		System.out.println(jedis.hvals("user"));
		jedis.close();
	}
	
	/**
	 * 获取Hash表所有字段的键
	 */
	public static void jedisGetHashFieldKeys() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		System.out.println(jedis.hkeys("user"));
		jedis.close();
	}
	
	/**
	 * 获取Hash表一个或者多个字段的值
	 */
	public static void jedisGetHashValues() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);
		List<String> user = jedis.hmget("user", "name", "age", "sex");
		System.out.println(user);
		jedis.close();
	}
	
	/**
	 * 给Hash表添加值
	 */
	public static void jedisAddToHash() {
		Jedis jedis = new Jedis("127.0.0.1", 6379);

		Map<String, String> map = new HashMap<String, String>();
		map.put("name", "zhangsan");
		map.put("age", "22");
		map.put("sex", "female");
		jedis.hmset("user", map);
		jedis.close();
	}
}
